package function;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Manager {
	private String id;//管理员id
	private String username;
	private String password;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	/*
	 * match方法判断用户名和密码是否匹配
	 * 在管理员登录时调用，在main类中调用
	 */
	public boolean match(String username, String password) {
		// 创建文件工厂实例，获取DOM解析器工厂
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// 如果创建的解析器在解析XML文档时必须删除元素内容中的空格，则为true，否则为false
		dbf.setIgnoringElementContentWhitespace(true);
		//保存管理员信息的xml文件路径
		String xmlPath = "manager.xml";

		try {
			// 创建解析器，解析XML文档
			DocumentBuilder db = dbf.newDocumentBuilder();
			// 使用dom解析xml文件
			Document xmldoc = db.parse(xmlPath);
			// 获取根节点
			Element root = xmldoc.getDocumentElement();
			//构建str用于查询满足特定条件的结点
			String str = "/managerList/manager/username[text()='" + username + "']/parent::*";
			//将str作为参数传入selectSingleNode方法查找满足条件的结点
			Element son = (Element) selectSingleNode(str, root);

			if (son != null) {//若存在此管理员
				for (Node node = son.getFirstChild(); node != null; node = node.getNextSibling()) {
					// 判断是否为元素节点
					if (node.getNodeType() == Node.ELEMENT_NODE) {
						String name0 = node.getNodeName();
						String value = node.getFirstChild().getNodeValue();
						//若用户名密码匹配返回true
						if ("password".equals(name0)) {
							if (password.equals(value))
								return true;
						}
					}
				}
			}			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
		return false;
	}
	/*
	 * 由于文本文件均采用xml格式，selectSingleNode方法在对四个xml文件进行操作的类
	 * Manager类，Notice类，Edge类，Scenic类中均有
	 * 此方法用于查询结点（xml为树型结构），且此方法只返回单个结点
	 */
	private static Node selectSingleNode(String express, Element source) {
		// 创建XPath工厂
		XPathFactory xpathFactory = XPathFactory.newInstance();
		// 创建XPath对象
		XPath xpath = xpathFactory.newXPath();

		Node result = null;
		try {
			//计算XPath表达式
			result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			System.out.println(e.getMessage());
		}
		//返回目标结点
		return result;
	}
	
}
